<template>
  <div class="blog-toc-container">
    <h2 class="title">目录</h2>
    <RightList @click="handleClick" :list="tocList" />
  </div>
</template>

<script>
import RightList from "./RightList.vue";

export default {
  components: {
    RightList,
  },
  props: {
    toc: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      activeAnchor: "",
    };
  },
  created() {
    this.$bus.$on("mainScroll", this.handleMainScroll);
    console.log(this.tocList);
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.handleMainScroll);
  },
  computed: {
    tocList() {
      const getTocList = (toc) => {
        if (!toc) {
          return null;
        }
        return toc.map((item) => {
          return {
            name: item.name,
            anchor: item.anchor,
            children: getTocList(item.children),
            selected: item.anchor === this.activeAnchor,
          };
        });
      };
      return getTocList(this.toc);
    },
    tocDoms() {
      const doms = [];
      const getDomList = (toc) => {
        toc.forEach((item) => {
          const dom = document.querySelector(`#${item.anchor}`);
          doms.push(dom);
          if (item.children) {
            getDomList(item.children);
          }
        });
      };
      getDomList(this.toc);
      return doms;
    },
  },
  methods: {
    handleMainScroll(container) {
      if(!container){
        return;
      }
      this.activeAnchor = "";
      const form = container.querySelector("#form-container");
      if(form && form.getBoundingClientRect().top < 0){
        return;
      }
      const range = 200;
      for (let i = 0; i < this.tocDoms.length; i++) {
        const rect = this.tocDoms[i].getBoundingClientRect();
        if (rect.top >= -10 && rect.top <= range) {
          this.activeAnchor = this.tocDoms[i].id;
          return;
        } else if (rect.top < -10) {
          this.activeAnchor = this.tocDoms[i].id;
        } else {
          return;
        }
      }
    },
    handleClick(item) {
      location.hash = item.anchor;
    },
  },
};
</script>

<style scoped lang="less">
.blog-toc-container {
  width: 300px;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  .title {
    font-size: 20px;
    margin-bottom: 18px;
  }
}
</style>